package com.codingke.codingbookstore.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.codingke.codingbookstore.R;
import com.codingke.codingbookstore.utils.AppUtils;
import com.codingke.codingbookstore.vo.User;

import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends BaseActivity {

    private EditText editText_password,editText_phone;
    private ImageView imageView_show_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        editText_password = (EditText) findViewById(R.id.editText_password);
        editText_phone = (EditText) findViewById(R.id.editText_phone);
        imageView_show_password = (ImageView) findViewById(R.id.imageView_show_password);
    }

    public void forgetPasswordClick(View view){
        startActivity(new Intent(this,ResetPasswordActivity.class));
    }

    public void openRegisterClick(View view){
        startActivity(new Intent(this, RegisterActivity.class));
    }

    public void backClick(View view){
        finish();
    }


    private boolean showPassword = false;

    /**
     * 显示或隐藏密码
     * @param view
     */
    public void showHidePasswordClick(View view){
        if (showPassword){
            imageView_show_password.setSelected(true);
            editText_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            showPassword = false;
        }else{
            imageView_show_password.setSelected(false);
            editText_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            showPassword = true;
        }
    }

    /**
     * 登录事件方法
     * @param view
     */
    public void loginClick(View view){
        AppUtils.hideInputMethod(view);
        login();
    }

    /**
     * 用户登录
     */
    private void login() {
        String phone = editText_phone.getText().toString();
        if(TextUtils.isEmpty(phone)){
            showToast("请输入手机号");
            return;
        }
        String password = editText_password.getText().toString();
        if(TextUtils.isEmpty(password)){
            showToast("请输入密码");
            return;
        }
        User user = new User();
        user.setUsername(phone);
        user.setPassword(password);
        user.login(this, new SaveListener() {
            @Override
            public void onSuccess() {
                showToast("登录成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                showToast("登录失败");
            }
        });
    }
}
